<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:Clickr 訂單信息
 *@param datetime 2012-01-12
 *@param author abin
 ********************/
class Orders extends Admins_Controller {
  
  private $data=array();

  public function __construct(){
    parent::__construct();
    $this->data['currentPage']='orders';
    $this->data['format_time']=$this->settings['default_time'];
    $this->load->model('orders_mdl');
    //訂單狀態
	$this->data['lang'] =$this->lang->language;
    $this->data['orderStatus']=array(1=>$this->data['lang']['orders_lable_64'],2=>$this->data['lang']['orders_lable_65'],3=>$this->data['lang']['orders_lable_66'],4=>$this->data['lang']['orders_lable_67']);
  }

  public function index(){
    $this->get_list();
    $this->_get_total_year_fee();
    // $this->output->enable_profiler(true);
    $this->load->view('admins/orders_list_view',$this->data);
  }
  
  //獲取列表
  private function get_list(){
    $page = $this->input->get('p',TRUE);
    $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;
    $limit = $this->settings['default_admin_limit'];
    //$limit =1;
    $offset = ($page - 1) * $limit;
    if($offset < 0){
      redirect('admins/orders');
    }
    $url_query=$_SERVER['QUERY_STRING'];
    if(!empty($url_query)){
      $url_query=preg_replace('/&p=(\d+)/','',$url_query);
    }
    // 保留查詢參數;
    $cookie = array(
        'name'   => 'url_query',
        'value'  => base64_encode($url_query),
        'expire' => '0',
        'path'   => '/',
    );
    $this->input->set_cookie($cookie);

    $this->data['nickname']=$this->input->get('nickname');
    $this->data['order_status_id']=$this->input->get('order_status_id');
    $this->data['phone']=$this->input->get('phone');
    $this->data['invoice_no']=$this->input->get('invoice_no');
    $this->data['table_num']=$this->input->get('table_num');
    $this->data['field']=$this->input->get('field');
    $this->data['sort']=$this->input->get('sort');
    $this->data['field']=!empty($this->data['field'])?$this->data['field']:'add_time';
    $this->data['sort']=!empty($this->data['sort'])?$this->data['sort']:'desc';
    
    $data=array('limits'=>$limit,'offset'=>$offset);
    $data=!empty($this->data['nickname'])?array_merge($data,array('nickname'=>trim($this->data['nickname']))):$data;
    $data=!empty($this->data['order_status_id'])?array_merge($data,array('order_status_id'=>trim($this->data['order_status_id']))):$data;
    $data=!empty($this->data['phone'])?array_merge($data,array('phone'=>trim($this->data['phone']))):$data;
    $data=!empty($this->data['invoice_no'])?array_merge($data,array('invoice_no'=>$this->data['invoice_no'])):$data;  
	$data=!empty($this->data['table_num'])?array_merge($data,array('table_num'=>$this->data['table_num'])):$data;
    
    $data=!empty($this->data['field'])?array_merge($data,array('field'=>$this->data['field'])):$data;
    $data=!empty($this->data['sort'])?array_merge($data,array('sort'=>strtoupper($this->data['sort']))):$data;
        
    $this->data['lists_count']=$this->orders_mdl->totle_orders($data);
    
    $pagination = '';
    if($this->data['lists_count'] > $limit)
    {
      $this->dpagination->currentPage($page);
      $this->dpagination->items($this->data['lists_count']);
      $this->dpagination->limit($limit);
      $this->dpagination->adjacents(5);
      $this->dpagination->target(site_url('admins/orders').'?'.$url_query);
      $this->dpagination->parameterName('p');
      $this->dpagination->nextLabel($this->data['lang']['orders_lable_19']);
      $this->dpagination->PrevLabel($this->data['lang']['orders_lable_18']);
      $pagination = $this->dpagination->getOutput();
    }
    $this->data['pagination'] = $pagination;
    $this->data['lists']=$this->orders_mdl->get_orders($data);
  }
  /*统计报告*/
  public function report(){
    $endTime = $this->input->get('endDate');
    $isExport = $this->input->get('isExport');
    $startTime = $this->input->get('satrtDate');
    $endTime = empty($endTime) ? strtotime(date('Y-m-d',time())) : strtotime($endTime)+86399;

    $startTime = empty($startTime) ? $endTime-(86400*7) : strtotime($startTime);//默認7天的數據
    $where = "add_time > ".$startTime." and add_time <= ".$endTime;
    //$sql = "select count(*) as nums,sum(total) as total,from_unixtime(add_time,'%Y-%m-%d') as order_date from clickrcms_order where ".$where." group by order_date order by add_time desc";
    $sql = "select * from clickrcms_order where ".$where."  order by add_time desc";
    $query = $this->db->query($sql);
     $orders = $query->result_array();
     $baseOrders = array(); 
     foreach($orders as $order){
         $key = date('Y-m-d',$order['add_time']);
         $baseOrders[$key]['nums'] += 1;
         $baseOrders[$key]['total'] += $order['total'];
         $baseOrders[$key]['order_date'] = $key;
     }
     $this->data['orders']= $baseOrders;
    $this->data['startDate'] = date('Y-m-d',$startTime);
    $this->data['endDate'] = date('Y-m-d',$endTime);
    
    $this->data['results'] = $this->orders_mdl->get_order_products($where);
    if($isExport == 1){
        $this->export();
    }
    $this->load->view('admins/orders_report_view',$this->data);
  }
  //獲取的總額
  private function _get_total_year_fee(){
    $query=$this->db->select_sum('total')->get('clickrcms_order');
    $total_year_fee=0;
    if(!empty($query) && $query->num_rows()>0){
      $result=$query->row_array();
      $total_year_fee=$result['total'];
    }
    $this->data['total_year_fee']=$total_year_fee;
  }
  
  //顯示詳細
  public function view($view_id=0){
    if(!empty($view_id) && intval($view_id)>0){
      // $data=array('language_id'=>$this->settings['default_language'],'id'=>$view_id);
      // $this->data['list_one']=!empty($query)?$query->row_array():'';
      $this->data['list_one']=$this->orders_mdl->get_orders_by_id($view_id);
      //var_dump($this->data['list_one']);exit;
      $this->_get_order_products($view_id);//獲取購買產品
      //$this->_get_order_history($view_id);//獲取訂單記錄
      $this->load->view('admins/orders_show_view',$this->data);
    }
  }

  //訂單詳情的購買產品信息
  private function _get_order_products($order_id){
    if (!empty($order_id) && intval($order_id)>0) {
      $this->load->model('ordersproduct_mdl');
      $this->data['products']=$this->ordersproduct_mdl->get_ordersproduct(array('order_id'=>$order_id));
    }
  }

  //訂單詳情 記錄
  public function _get_order_history($order_id){
    if (!empty($order_id) && intval($order_id)>0) {
      $this->load->model('ordershistory_mdl');
      $this->data['historys']=$this->ordershistory_mdl->get_ordershistory(array('order_id'=>$order_id));
    }
  }
  
    
  //刪除諮詢
  public function delete($delete_id=0){
    if(!empty($delete_id)){
      $result=$this->orders_mdl->delete_orders($delete_id);
      $this->operator_log('刪除訂單管理->ID:'.$delete_id,'刪除',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      redirect("admins/orders");
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }
   //批量刪除
  public function delete_batch(){
    $delete_string=$this->input->get('delete_string');
    if(!empty($delete_string)){
      $del_arr=explode(',',$delete_string);
      $result=$this->orders_mdl->delete_batch($del_arr);
      $this->operator_log('批量刪除訂單管理->ID:'.$delete_string,'批量刪除',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      redirect("admins/orders");
    }else{
      show_error('對不起,參數出錯');
      exit;
    }
  }

  //修改訂單信息
  public function history(){
    $order_id=$this->input->post('order_id');
    if (!empty($order_id) && intval($order_id)>0) {
      $notify=$this->input->post('notify');
      $order_status_id=$this->input->post('order_status_id');
      $data=array(
        'order_id'=>$order_id,
        'order_status_id'=>$order_status_id,
        'notify'=>$notify,
        'comment'=>$this->input->post('comment'),
        'add_time'=>time()
      );
      $this->load->model('ordershistory_mdl');
      $result=$this->ordershistory_mdl->add_ordershistory($data);
      if($result && !empty($order_status_id)){
        $this->orders_mdl->edit_orders(array('order_status_id'=>$order_status_id),$order_id); //更改訂單信息
      }
      $this->operator_log('更新訂單->ID:'.$order_id,'更新訂單',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      redirect("admins/orders/view/".$order_id);

    }else{
      show_error('對不起,參數出錯');
      exit;
    }
  }

  //進行積分處理
  public function integral($order_id){
    if(!empty($order_id) && is_numeric($order_id)>0){
      $query=$this->orders_mdl->get_orders_by_id($order_id);
      $symbol=$this->input->get('symbol');//計算分數.
      if(empty($query))
        show_error('參數不對.沒有該ID信息');

      $this->load->model('integral_mdl');
      $this->load->model('integralhistory_mdl');
      $row=$this->integral_mdl->get_one_integral(array('phone'=>$query['phone']));
      $order_result=$this->orders_mdl->edit_orders(array('order_status_id'=>$symbol),$order_id); //更改訂單信息
      $result=$order_result;
      $integral_status=$this->_get_integral_status();//判斷是否啟用積分
      if(!empty($order_result) && $order_result>0 && $integral_status){//狀態修改成功
        $integral_data=array(
          'phone'=>$query['phone'],
          'integral'=>intval($query['total']),
          'update_time'=>time(),
          'add_time'=>time(),
        );
        $integral_history=array(
          'admin_name'=>$this->nsession->userdata('nick_name'),
          'notify'=>1,
          'score'=>intval($query['total']),
          'comment'=>'訂單完成加積分,積分加:'.intval($query['total']).',訂單號:'.$query['invoice_no'],
          'add_time'=>time(),
        );
        if(!empty($symbol) && $symbol==2){ //新增積分
          $integral_id=0;
          if(!empty($row) && is_array($row)){ //積分存在電話號碼
            unset($integral_data['add_time']);
            $integral_data['integral']=intval($query['total'])+$row['integral'];
            $integral_history['score']=$row['integral'];
            $integral_id=$row['id'];
            $result+=$this->integral_mdl->edit_integral($integral_data,$integral_id);
          }else{ //不存在
            $integral_id=$this->integral_mdl->add_integral($integral_data);
          }
        }else{ //扣除積分
          if(!empty($row) && is_array($row)){ //積分存在電話號碼
            unset($integral_data['add_time']);
            $integral_history['notify']=2;
            if($row['integral']-intval($query['total'])>=0){
              $integral_data['integral']=$row['integral']-intval($query['total']);
            }else{
              $integral_data['integral']=0;
              $integral_history['score']=$row['integral'];
            }
            $integral_history['comment']='訂單取消完成扣積分,積分減:'.$integral_history['score'].',訂單號:'.$query['invoice_no'];
            $integral_id=$row['id'];
            $result+=$this->integral_mdl->edit_integral($integral_data,$integral_id);
          }
        }
        if($integral_id){//積分新增成功,新增 加積分記錄
          $integral_history['integral_id']=$integral_id;
          $result+=$this->integralhistory_mdl->add_integralhistory($integral_history);
        }
      }
      $this->operator_log('更新訂單狀態,變更積分->ID:'.$order_id,'更新訂單',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      $redirect=site_url('admins/orders').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
    }else{
      show_error('對不起,參數出錯');
      exit;
    }
  }

  //判斷是否啟用積分功能
  private function _get_integral_status(){
    //獲取是否啟用積分
    $setting=array(
      'group'=>'other',
      'key'=>'integral_status'
    );
    $query=$this->settings_mdl->get_settings_by_where($setting);
    $integral_status=$query['value'];
    return $integral_status==1?TRUE:FALSE;
  }
  /*导出数据*/
  private function export(){
      error_reporting(0);
      $this->load->library('PHPExcel');
      $this->load->library('PHPExcel/PHPExcel_IOFactory');
      $fileName = iconv("utf-8", "gb2312","orders-".date('Y-m-d').".xlsx");
      $objPHPExcel = new \PHPExcel();
      $sheet = $objPHPExcel->getActiveSheet();
      $header = array('日期','總額','單數');
      $i=1;
      foreach($header as $k=>$name){
          $sheet->setCellValue(mchr($k).$i,$name);
      }
      $total_add = $count_all = 0;
      /*设置商品名称*/
      $ks=0;
      $sheet->getColumnDimension('A')->setWidth(12);
      foreach($this->data['results']['prodcuts'] as $p_id=>$pname){
          $sheet->setCellValue(mchr($ks+3).$i,$pname);
          $sheet->getColumnDimension(mchr($ks+3))->setWidth(13);
          $ks++;
      }
      $i++;
      $orders = $this->data['orders'];
      $base = $this->data['results']['base'];
      foreach ($orders as $key => $order) {
          $sheet->setCellValue(mchr(0).$i,date('Y/m/d',strtotime($order['order_date'])));
          $sheet->setCellValue(mchr(1).$i,$order['total']);
          $sheet->setCellValue(mchr(2).$i,$order['nums']);
          $_i=3;/*设置商品数量*/
          foreach($this->data['results']['prodcuts'] as $_id=>$_name){
              $sheet->setCellValue(mchr($_i).$i,isset($base[$order['order_date']][$_id]) ? $base[$order['order_date']][$_id] : 'N');
              $_i++;
          }
          $total_add += $order['total'];
          $count_all += $order['nums'];
          $i++;
      }
      $sheet->mergeCells('A'.$i.':'.mchr(count($this->data['results']['prodcuts'])+2).$i);//合并两行
      $sheet->setCellValue('A'.$i,' 營業總額：HK$ '.$total_add.'　　　　　 營業總單： '.$count_all);
      $sheet->getStyle('A1'.':'.mchr(count($this->data['results']['prodcuts'])+2).$i)->getBorders()->getAllBorders()->setBorderStyle('thin');
      $objProps = $objPHPExcel->getProperties();
      $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
      //var_dump($objWriter);
      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
      header("Content-Type:application/force-download");
      header("Content-Type:application/vnd.ms-execl");
      header("Content-Type:application/octet-stream");
      header("Content-Type:application/download");
      header('Content-Disposition:attachment;filename="'.$fileName.'"');
      header("Content-Transfer-Encoding:binary");
      $objWriter->save('php://output'); //文件通过浏览器下载
      return null;
  }

}